//
//  LHStatus.swift
//  sinaWeibo
//
//  Created by LiHong on 15/10/31.
//  Copyright © 2015年 LiHong. All rights reserved.
//

import UIKit
import SDWebImage

class LHStatus: NSObject {
    /// 微博创建时间
    var created_at: String?
    /// 字符串型的微博ID
    var id: Int = 0
    /// 微博信息内容
    var text: String?
    /// 微博来源
    var source: String?
    /// 微博的配图
    var pic_urls: [[String: AnyObject]]? {
        didSet{
            let count = pic_urls?.count ?? 0
            
            if count == 0 {
                return
            }
            
            largeStorePictureURLs = [NSURL]()
            
            storePictureURLs = [NSURL]()
            for dict in pic_urls! {
                if let urlString = dict["thumbnail_pic"] as? String {
                    
                    storePictureURLs?.append(NSURL(string: urlString)!)
                    
                    let largeUrlString = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
                    largeStorePictureURLs?.append(NSURL(string: largeUrlString)!)
                  
                }
            }
         }
    }
    
    /// 返回微博配图对应的URL数组
    private var storePictureURLs: [NSURL]?
    
    /// 返回微博配图的大图数组
    private var largeStorePictureURLs: [NSURL]?
    
    /// 计算型属性
    var pictureURL: [NSURL]? {
        get {
            return retweeted_status == nil ? storePictureURLs : retweeted_status!.storePictureURLs
        }
    }
    
    var largePicURLs: [NSURL]? {
        get {
            return retweeted_status == nil ? largeStorePictureURLs : retweeted_status!.largeStorePictureURLs
        }
    }
    
    /// 用户模型
    var user: LHUser?
    /// 行高
    var rowHeight: CGFloat?
    
    /// 被转发的微博
    var retweeted_status: LHStatus?
    
    /// 返回微博cell对应的identifier
    func cellId() -> String {
        return retweeted_status == nil ? LHStatusCellReuseIdentifier.NormalCell.rawValue : LHStatusCellReuseIdentifier.RetweetCell.rawValue
        
    }
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    // 字典的key在模型中找不到对应的值
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String {
        let p = ["created_at", "idstr", "text", "source", "pic_urls", "user", "retweeted_status"]
        
        return "\n\t微博模型:\(dictionaryWithValuesForKeys(p))"
    }
    
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user" {
            if let dict = value as? [String: AnyObject] {
                user = LHUser(dict: dict)
                return
            }
            
        } else if key == "retweeted_status" {
            
            if let dict = value as? [String: AnyObject] {
                
                retweeted_status = LHStatus(dict: dict)
     //           print("retweeted_status = \(retweeted_status)")
            }
            return
            
        }
        return super.setValue(value, forKey: key)
    }
    
    
    /// 加载微博数据
    class func loadStatus(since_id: Int, max_id: Int, finished: (statuses: [LHStatus]?, error:NSError?) -> ()) {
        LHNetWorkTools.shareInstance.loadStatus(since_id, max_id: max_id) { (result, error) -> () in
            if error != nil {
                print("error = \(error)")
                finished(statuses: nil, error: error)
                return
            }
            // 判断是否有数据
            if let array = result?["statuses"] as? [[String: AnyObject]] {
                // 有数据
                // 创建模型数组
                var statuses = [LHStatus]()
                
                for dict in array {
                    statuses.append(LHStatus(dict: dict))
                    
                }
                // 字典转模型完成
                // 缓存图片
                self.cacheWebImage(statuses ,finished: finished)
              //  print("statuses = \(statuses)")
                //finished(statuses: statuses, error: nil)
                
            }else{
                // 没有数据
                finished(statuses: nil, error: nil)
            }
            
            
        }
    }
    
    class func cacheWebImage(statuses: [LHStatus]?, finished: (statuses: [LHStatus]?, error:NSError?) -> ()){
        // 创建任务组
        let group = dispatch_group_create();
        
        // 判断是否有模型
        guard let list = statuses else {
            // 进来代表没有模型
            return
        }
        ///图片缓存图片大小
        var length = 0
        // 遍历模型
        for status in list {
            let count = status.pictureURL?.count ?? 0
            if count == 0 {
                // 没有图片，遍历下一个模型
                continue
            }
            
            // 判断是否有图片可以下载
            if let urls = status.pictureURL {
                // 当图片只有一张的时候，缓存
                if urls.count == 1 {
                    let url = urls[0]
                    dispatch_group_enter(group)
                    
                    SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, error, _, _, _) -> Void in
                        dispatch_group_leave(group)
                        
                        // 下载图片出错
                        if error != nil {
                            print("下载图片出错")
                            return
                        }
                        
                        // 没有出错
                        print("图片下载完成")
                        
                        // 记录下载图片大小
                        if let data = UIImagePNGRepresentation(image) {
                            length += data.length
                        }
                    })
                }
            }
            
            
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            print("所有图片下载完成,告诉调用者获取到了微博数据: 大小:\(length / 1024)")
            finished(statuses: statuses, error: nil)
            
        }
    }
}
